package com.app.community.service;

import com.app.community.model.entity.Question;
import com.app.community.mapper.CardMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;

/**
 *
 * card页面的service层
 * 2020/10/15 20:25
 **/
@Service
public class CardService {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    CardMapper cardMapper;

    @Autowired
    NotificationService notificationService;

    public Question selectQuestionById(Long questionId) {
        Question question = cardMapper.selectQuestionById(questionId);
        // 增加浏览量
        updateQuestionViewCountByRedis(questionId);
        // 获取MySQL中的浏览量
        Integer browseCount = question.getBrowseCount();
        // 获取redis中的浏览量
        Integer temp = Integer.parseInt((String) Objects.requireNonNull(redisTemplate.opsForValue().get(questionId.toString())));
        question.setBrowseCount(browseCount + temp);
        return question;
    }

    /**
     * 点赞或取消点赞
     */
    public Long likeOrDisLike(Long questionId, String userId) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());

        Integer temp = cardMapper.ifLike(userId, questionId);

        if (temp == null) {
            // 如果用户未点赞则添加点赞，添加通知
            cardMapper.like(userId, time, questionId);
            notificationService.insertLikeNotification(questionId,userId);
        } else if (temp == 1) {
            // 如果用户已点赞则取消则删除点赞，删除通知
            cardMapper.dislike(userId, questionId);
            notificationService.deleteNotification(questionId,userId);
        }

        return cardMapper.likeCount(questionId);
    }

    /**
     * 返回点赞数量
     */
    public Long likeCount(Long questionId) {
        return cardMapper.likeCount(questionId);
    }


    /**
     * MySQL更新浏览数
     */
    private void updateQuestionViewCount(Integer browseCount, Long questionId) {
        cardMapper.updateQuestionViewCount(browseCount, questionId);
    }


    /**
     * redis更新浏览数
     */
    private void updateQuestionViewCountByRedis(Long questionId) {
        redisTemplate.opsForValue().increment(questionId.toString());
    }

    /**
     * 每五分钟把Redis的浏览量写入MySQL
     */
    @Scheduled(fixedRate = 300000)
    private void writeBrowseCountIntoMySQL(){
        Set<String> keys =  redisTemplate.keys("*");
        assert keys != null;
        for (String key : keys) {
            // 写入mysql
            Long questionId = Long.parseLong(key);
            Integer temp = Integer.parseInt((String) Objects.requireNonNull(redisTemplate.opsForValue().get(questionId.toString())));
            updateQuestionViewCount(temp, questionId);
            // 删除key
            redisTemplate.delete(questionId.toString());
        }
    }

}
